<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                 |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarDealer;

use AuctionCore\AntNest\UserCenter;
use AuctionCore\System\SystemConf;

/**
 * 维保记录查询
 *
 * @author Xmh
 */
class RepairCheck
{

    private $DealerRepairLog;
    private $ThirdRepairLog;
    private $DealerRepairPayLog;
    private $CarRepairInfo;

    public function __construct()
    {
        $this->DealerRepairLog = M('dealer_repair_log');
        $this->ThirdRepairLog = M('third_repair_log');
        $this->DealerRepairPayLog = M('dealer_repair_pay_log');
        $this->CarRepairInfo = M('car_repair_info');
    }

    /**
     * 获取车商维保查询记录
     *
     * @param $page
     * @param $limit
     * @param $params
     */
    public function get_dealer_repair_check_list($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索
        $map = [];
        if ($params['vin']) {
            $map['drl.vin'] = ['eq', $params['vin']];
        }
        if ($params['status'] == 2) {
            $map['drl.type'] = ['in', [1, 2]];
        }
        if ($params['check_accounts']) {
            $map['drl.search_state'] = ['eq', 2];
        }
        if ($params['dealer_id'] > 0) {
            $map['drl.dealer_id'] = ['eq', $params['dealer_id']];
        }
        if ($params['start_time']) {
            $map['drl.createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
        }
        if ($params['end_time']) {
            $map['drl.createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['drl.createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
        }
        if ($params['data_from']) {
            switch ($params['data_from']) {
                case 1:
                    $data_comefrom = 3;
                    break;
                case 2:
                    $data_comefrom = 2;
                    break;
                case 3:
                    $data_comefrom = 1;
                    break;
                default:
                    break;
            }
            if ($data_comefrom > 0) {
                $map['drl.type'] = ['eq', $data_comefrom];
            }
        }
        if ($params['order_status'] > 0) {
            if ($params['order_status'] == 3) {
                $map['drl.search_state'] = ['in', [0, 3]];
            } else {
                $map['drl.search_state'] = ['eq', $params['order_status']];
            }
        }
        if ($params['dealer_info']) {
            $mobile_rules = "/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|17[0-9]{9}|18[0-9]{9}$/";
            if (preg_match($mobile_rules, $params['dealer_info'])) {
                $uc = new UserCenter();
                $result = $uc->info_bymobile($params['dealer_info'], 2);
                if (!empty($result)) {
                    $where['du.uid'] = $result['account_id'];
                }
            } else {
                $where['cd.dealer_id'] = ['eq', $params['dealer_info']];
                $where['cd.contact_person'] = ['like', '%' . $params['dealer_info'] . '%'];
                //$where['cd.contact_mobile'] = ['like', '%' . $params['dealer_info'] . '%'];

                $where['_logic'] = 'OR';
            }
            $map['_complex'] = $where;
        }
        if ($params['third_channel'] > 0) {
            $map['drl.type'] = ['eq', $params['third_channel']];
        }
        if ($params['is_bill'] > -1) {
            $map['drl.pay_state'] = ['eq', $params['is_bill']];
        }

        $cols = 'drl.*,cd.dealer_id,cd.contact_person,c.car_id,du.uid';
//        ',c.brand_id,c.series_id,c.model_id'
        $prefix = C('DB_PREFIX');
        $total = $this->DealerRepairLog->alias('drl')
            ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
            ->join($prefix . 'dealer_user as du ON du.dealer_id = cd.dealer_id')
            ->join(' LEFT JOIN (SELECT MAX(car_id) as car_id,vin FROM ' . $prefix . 'cars GROUP BY vin) as c ON drl.vin = c.vin')
            ->where($map)->count();
        $order = 'drl.id DESC';
        $list = $this->DealerRepairLog->alias('drl')->field($cols)
            ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
            ->join($prefix . 'dealer_user as du ON du.dealer_id = cd.dealer_id')
            ->join(' LEFT JOIN (SELECT MAX(car_id) as car_id,vin FROM ' . $prefix . 'cars GROUP BY vin) as c ON drl.vin = c.vin')
            ->where($map)
            ->limit($limit)
            ->page($page)
            ->order($order)
            ->select();
        if (!empty($list)) {
            $list = Dealer::get_contact_mobile_byAntNest($list);
        }
        /*print_r($list);die;*/
//        echo M()->_sql();
        if (!empty($list)) {
            $finance_price = SystemConf::getConfByName('REPAIR_FINANCE_SINGL_PRICE');
            $finance_price = json_decode($finance_price['value'], true);
            $uidArr = [];
            foreach ($list as $key => $val) {
                $list[$key]['car_match'] = 0;
                if(empty($val['brand'])){
                    $list[$key]['brand'] = '...';
                }
                if(empty($val['series_model'])){
                    $list[$key]['series_model'] = '...';
                }
                if ($val['car_id'] > 0) {
                    $list[$key]['car_match'] = 1;
                }
                $list[$key]['build_time'] = $val['build_time'] ? $val['build_time'] : "...";
                $list[$key]['check_time'] = $val['createtime'] ? $val['createtime'] : "...";
                $search_state_name = $val['search_state'] ? C('DEALER_REPAIR_CHECK_SEARCH_STATUS')[$val['search_state']] : '查询失败';
                $list[$key]['search_state_name'] = $search_state_name;
                if ($val['search_state'] == 3) {
                    $pay_state = 2;
                    $pay_price = 0;
                } else {
                    $pay_state = $val['pay_state'];
                    $pay_price = $val['price'];
                }
                $list[$key]['pay_state_name'] = C('DEALER_REPAIR_PAY_STATUS')[$pay_state];
                $list[$key]['price'] = $pay_price;
                /*if ($val['check_type'] == 1) {    //查博士
                    $list[$key]['finance_price'] = $finance_price['chaboshi'];
                } else {
                    $list[$key]['finance_price'] = $finance_price['chejianding'];
                }*/
                switch ($val['type']) {
                    case 1:
                        $data_comefrom = 3;
                        break;
                    case 2:
                        $data_comefrom = 2;
                        break;
                    case 3:
                        $data_comefrom = 1;
                        break;
                    default:
                        break;
                }
                $list[$key]['data_comefrom'] = C('DEALER_REPAIR_COME_FROM')[$data_comefrom];
                $list[$key]['third_party_name'] = C('DEALER_REPAIR_CHECK_THIRD_PARTY')[$val['check_type']];
                $uidArr[] = $val['uid'];
            }
        }
        $userList = array();
        if (!empty($uidArr)) {
            $uc = new UserCenter();
            $userList = $uc->batchInfo($uidArr, 2);
        }
        $result = array(
            'list' => $list,
            'user_list' => $userList['list'],
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取第三方接口查询记录
     *
     * @param $page
     * @param $limit
     * @param $params
     */
    public function get_third_repair_check_list($params)
    {
        $uc = new UserCenter();
        $data = $uc->get_repair_check_list($params);
        foreach($data['list'] as $key => $val){
            $list[$key]['id'] = $val['id'];
            $list[$key]['vin'] = $val['vin'];
            $list[$key]['check_platform'] = $val['callertype'];  //来源 1 315C 2 来拍车
            $list[$key]['search_state'] = $val['search_status'];
            $list[$key]['search_state_name'] = C('DEALER_REPAIR_CHECK_SEARCH_STATUS')[$val['search_status']];
            $list[$key]['check_type'] = $val['type']; // 1查博士 2 车鉴定
            $list[$key]['check_time'] = $val['createtime']; //查询时间
            $list[$key]['build_time'] = $val['maketime']; //查询时间
            if(!empty($val['callertype'])){
                $list[$key]['check_platform_name'] =  C('DEALER_REPAIR_CHECK_PLATFORM')[$val['callertype']];
            }else{
                $list[$key]['check_platform_name'] = '....';
            }
            $list[$key]['third_party'] = $val['type'];
            $list[$key]['third_party_name'] = C('DEALER_REPAIR_CHECK_THIRD_PARTY')[$val['type']];
            $list[$key]['car_match'] = 0;
            $car = M('cars')->field('max(car_id) as car_id')->where("vin = '".$val['vin']."'")->group('vin')->find();
            if($car['car_id']>0 && !empty($val['model'])){
                $list[$key]['car_match'] = 1;
                $list[$key]['car_id'] = $car['car_id'];
            }
            $list[$key]['series_model'] = $val['model'] ? $val['model'] : '...';
            $list[$key]['brand'] = $val['manufacturer'] ? $val['manufacturer'] : '...';
            $search_state_name = $val['search_status'] ? C('DEALER_REPAIR_CHECK_SEARCH_STATUS')[$val['search_status']] : '查询失败';
            $list[$key]['search_state_name'] = $search_state_name;
        }
       $result = [
            'list' => $list,
            'total' => $data['count']
        ];
        return $result;
    }

    /**
     * 第三方接口对账接口
     *
     * @param $page
     * @param $limit
     * @param $params
     */
    public function get_repair_info_list($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索
        $map = [];
        if ($params['vin']) {
            $map['cri.vin'] = ['eq', $params['vin']];
        }
        if ($params['check_platform']) {
            $map['cri.type'] = ['eq', $params['check_platform']];
        }
        if ($params['start_time']) {
            $map['trl.createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
        }
        if ($params['end_time']) {
            $map['trl.createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['trl.createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
        }
        if ($params['third_channel'] > 0) {
            $map['cri.third_party'] = ['eq', $params['third_channel']];
        }
        $cols = 'cri.rid as id,cri.vin,cri.type as check_platform,cri.createtime as build_time,cri.normalrepairrecords,cri.third_party,
                 trl.search_state,trl.createtime as check_time,c.car_id';
        $prefix = C('DB_PREFIX');
        $total = $this->CarRepairInfo->alias('cri')
//            ->join(' LEFT JOIN ' . $prefix . 'third_repair_log as trl ON cri.vin = trl.vin and trl.search_state = 2')
//            ->join(' LEFT JOIN (SELECT MIN(id) as id,vin,search_state,createtime FROM ' . $prefix . 'third_repair_log GROUP BY vin) as trl ON cri.vin = trl.vin and trl.search_state = 2')
            ->join(' LEFT JOIN (SELECT MIN(id) as id,vin,search_state,createtime FROM ' . $prefix . 'third_repair_log WHERE search_state = 2 GROUP BY vin) as trl ON cri.vin = trl.vin')
            ->join(' LEFT JOIN (SELECT MAX(car_id) as car_id,vin FROM ' . $prefix . 'cars GROUP BY vin) as c ON cri.vin = c.vin')
            ->where($map)->count();
        $order = 'cri.rid DESC';
        $list = $this->CarRepairInfo->alias('cri')->field($cols)
//            ->join(' LEFT JOIN ' . $prefix . 'third_repair_log as trl ON cri.vin = trl.vin and trl.search_state = 2')
            ->join(' LEFT JOIN (SELECT MIN(id) as id,vin,search_state,createtime FROM ' . $prefix . 'third_repair_log WHERE search_state = 2 GROUP BY vin) as trl ON cri.vin = trl.vin')
            ->join(' LEFT JOIN (SELECT MAX(car_id) as car_id,vin FROM ' . $prefix . 'cars GROUP BY vin) as c ON cri.vin = c.vin')
            ->where($map)
            ->limit($limit)
            ->page($page)
            ->order($order)
            ->select();
//        echo M()->_sql();
        if (!empty($list)) {
            $finance_price = SystemConf::getConfByName('REPAIR_FINANCE_SINGL_PRICE');
            $finance_price = json_decode($finance_price['value'], true);
            foreach ($list as $key => $val) {
                $normalrepairrecords = !empty($val['normalrepairrecords']) ? unserialize($val['normalrepairrecords']) : '';
                $list[$key]['car_match'] = 0;
                if (!empty($normalrepairrecords)) {
                    if ($val['third_party'] == 1) {
                        $list[$key]['brand'] = $normalrepairrecords['brand'];
                        $modelName = $normalrepairrecords['modelName'];
                        if ($val['car_id'] > 0 && $modelName) {
                            $list[$key]['car_match'] = 1;
                        }
                        $list[$key]['series_model'] = $modelName ? $modelName : '...';
                    } elseif ($val['third_party'] == 2) {
                        if (!empty($normalrepairrecords['basic']['brand'])) {
                            $brand = $normalrepairrecords['basic']['brand'];
                        } elseif (!empty($normalrepairrecords['dataJson']['basic']['brand'])) {
                            $brand = $normalrepairrecords['dataJson']['basic']['brand'];
                        } else {
                            $brand = '...';
                        }
                        if (!empty($normalrepairrecords['basic']['model'])) {
                            $model = $normalrepairrecords['basic']['model'];
                        } elseif (!empty($normalrepairrecords['dataJson']['basic']['model'])) {
                            $model = $normalrepairrecords['dataJson']['basic']['model'];
                        } else {
                            $model = '...';
                        }
                        $list[$key]['brand'] = $brand;
                        if ($val['car_id'] > 0) {
                            $list[$key]['car_match'] = 1;
                        }
                        $list[$key]['series_model'] = $model;
                    }
                } else {
                    $list[$key]['brand'] = '...';
                    $list[$key]['series_model'] = '...';
                }
                $list[$key]['build_time'] = $val['build_time'] ? $val['build_time'] : "...";
                $list[$key]['check_time'] = $val['check_time'] ? $val['check_time'] : "...";
//                $search_state_name = $val['search_state'] ? C('DEALER_REPAIR_CHECK_SEARCH_STATUS')[$val['search_state']] : '查询失败';
                $list[$key]['search_state_name'] = '报告已生成';
                if ($val['search_state'] == 3) {
                    $pay_state = 2;
                    $pay_price = 0;
                } else {
                    $pay_state = $val['pay_state'];
                    $pay_price = $val['price'];
                }
                $list[$key]['pay_state_name'] = C('DEALER_REPAIR_PAY_STATUS')[$pay_state];
                $list[$key]['price'] = $pay_price;
                if ($val['third_party'] == 1) {    //查博士
                    $list[$key]['finance_price'] = $finance_price['chaboshi'];
                } else {
                    $list[$key]['finance_price'] = $finance_price['chejianding'];
                }
                if (!empty($val['check_platform'])) {
                    $check_platform_name = C('DEALER_REPAIR_CHECK_PLATFORM')[$val['check_platform']];
                } else {
                    $check_platform_name = '...';
                }
                $list[$key]['check_platform_name'] = $check_platform_name;
                $list[$key]['third_party_name'] = C('DEALER_REPAIR_CHECK_THIRD_PARTY')[$val['third_party']];
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取维保查询记录统计，查询次数，成功生成次数
     *
     * @param array $params
     *
     * @return array
     *
     */
    public function get_dealer_repair_check_count($params)
    {
        $type = 0;
        $yestoday = date("Y-m-d", strtotime('-1 day'));
        $map['drl.createtime'] = [['egt', $yestoday . ' 00:00:00'], ['elt', $yestoday . ' 23:59:59']];
        if ($params['vin']) {
            $map['drl.vin'] = ['eq', $params['vin']];
        }
        if ($params['status'] == 2) {
            $map['drl.type'] = ['in', [1, 2]];
        }
        if ($params['start_time']) {
            $map['drl.createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
            $type = 1;
        }
        if ($params['end_time']) {
            $map['drl.createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
            $type = 2;
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['drl.createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
            $type = 3;
        }
        if ($params['data_from']) {
            switch ($params['data_from']) {
                case 1:
                    $data_comefrom = 3;
                    break;
                case 2:
                    $data_comefrom = 2;
                    break;
                case 3:
                    $data_comefrom = 1;
                    break;
                default:
                    break;
            }
            if ($data_comefrom > 0) {
                $map['drl.type'] = ['eq', $data_comefrom];
            }
        }
        if ($params['order_status'] > 0) {
            if ($params['order_status'] == 3) {
                $map['drl.search_state'] = ['in', [0, 3]];
            } else {
                $map['drl.search_state'] = ['eq', $params['order_status']];
            }
        }
        if ($params['dealer_info']) {
            if (validatePhone($params['dealer_info'])) {
                $uc = new UserCenter();
                $info1 = $uc->info_ByMobile($params['dealer_info'], 2);
                $where['du.uid'] = array('eq', $info1['account_id']);
            } else {
                $where['cd.dealer_id'] = ['eq', $params['dealer_info']];
                $where['cd.contact_person'] = ['like', '%' . $params['dealer_info'] . '%'];
                $where['_logic'] = 'OR';
            }
            $map['_complex'] = $where;
        }
        if ($params['third_channel'] > 0) {
            $map['drl.type'] = ['eq', $params['third_channel']];
        }
        $prefix = C('DB_PREFIX');
        $total = $this->DealerRepairLog->alias('drl')
            ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->where($map)->count();
        $map['drl.search_state'] = 2;
        $total_success = $this->DealerRepairLog->alias('drl')
            ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
            ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->where($map)->count();
        $result = [
            'type' => $type,
            'total' => $total,
            'success_num' => $total_success,
        ];
        return $result;
    }

    /**
     * 获取维保查询第三方接口查询记录统计，查询次数，成功生成次数
     *
     * @param array $params
     *
     * @return array
     *
     */
    public function get_third_repair_check_count($params)
    {
        $type = 0;
        if ($params['begintime']) {
            $type = 1;
        }
        if ($params['endtime']) {
            $type = 2;
        }
        if ($params['begintime'] && $params['endtime']) {
            $type = 3;
        }
        $uc = new UserCenter();
        $data = $uc->get_repair_check_list($params);
        $result = [
            'type' => $type,
            'total' => !empty($data['request_count']) ? $data['request_count'] : 0,
            'success_num' => !empty($data['success_count']) ? $data['success_count'] : 0,
        ];
        return $result;
    }

    /**
     * 获取维保查询第三方接口对账查询记录统计，查询次数，产生金额
     *
     * @param array $params
     *
     * @return array
     *
     */
    public function get_dealer_repair_check_account_count($params)
    {
        $type = 0;
        $yestoday = date("Y-m-d", strtotime('-1 day'));
        $map['drl.createtime'] = [['egt', $yestoday . ' 00:00:00'], ['elt', $yestoday . ' 23:59:59']];
        if ($params['vin']) {
            $map['drl.vin'] = ['eq', $params['vin']];
        }
        if ($params['start_time']) {
            $map['drl.createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
            $type = 1;
        }
        if ($params['end_time']) {
            $map['drl.createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
            $type = 2;
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['drl.createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
            $type = 3;
        }
        if ($params['order_status'] > 0) {
            if ($params['order_status'] == 3) {
                $map['drl.search_state'] = ['in', [0, 3]];
            } else {
                $map['drl.search_state'] = ['eq', $params['order_status']];
            }
        }
        if ($params['dealer_info']) {
            $mobile_rules = "/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$/";
            if (preg_match($mobile_rules, $params['dealer_info'])) {
                $uc = new UserCenter();
                $info1 = $uc->infoByMobile($params['dealer_info'], 2);
                $where['du.uid'] = ['eq', $info1['account_id']];
            } else {
                $where['cd.dealer_id'] = ['eq', $params['dealer_info']];
                $where['cd.contact_person'] = ['like', '%' . $params['dealer_info'] . '%'];
                //$where['cd.contact_mobile'] = ['like', '%' . $params['dealer_info'] . '%'];
                $where['_logic'] = 'OR';
            }
            $map['_complex'] = $where;
        }
        if ($params['third_channel'] > 0) {
            $map['drl.type'] = ['eq', $params['third_channel']];
        }
        $map['search_state'] = ['eq', 2];
        $prefix = C('DB_PREFIX');
        //是否结算
        if ($params['is_bill'] > -1) {
            $map['drl.pay_state'] = ['eq', $params['is_bill']];
        }
        //数据来源
        if ($params['data_from']) {
            switch ($params['data_from']) {
                case 1:
                    $data_comefrom = 3;
                    break;
                case 2:
                    $data_comefrom = 2;
                    break;
                case 3:
                    $data_comefrom = 1;
                    break;
                default:
                    break;
            }
            if ($data_comefrom > 0) {
                $map['drl.type'] = ['eq', $data_comefrom];
                if ($data_comefrom == 1) { //查博士
                    $total_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                    $cbs_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                    $cjd_success = 0;
                    $c315_success = 0;
                } elseif ($data_comefrom == 2) { //车鉴定
                    $total_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                    $cjd_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                    $cbs_success = 0;
                    $c315_success = 0;
                } else {
                    $total_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                    $cbs_success = 0;
                    $cjd_success = 0;
                    $c315_success = $this->DealerRepairLog->alias('drl')
                        ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                        ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                        ->where($map)->count();
                }
            }
        } else {
            $total_success = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->count();
            $map['drl.type'] = ['eq', 1];
            $cbs_success = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->count();
            $map['drl.type'] = ['eq', 2];
            $cjd_success = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->count();
            $map['drl.type'] = ['eq', 3];
            $c315_success = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->count();
            unset($map['drl.type']);
        }
        //是否结算
        if ($params['is_bill'] > -1) {
            if ($params['is_bill'] == 0) {
                $settled = 0;
                $not_settled = $this->DealerRepairLog->alias('drl')
                    ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                    ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                    ->where($map)->sum('drl.price');
                $not_settled = $not_settled + 0;
            } else {
                $not_settled = 0;
                $settled = $this->DealerRepairLog->alias('drl')
                    ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                    ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                    ->where($map)->sum('drl.price');
                $settled = $settled + 0;
            }
        } else {
            $map['drl.pay_state'] = ['eq', 0];
            $not_settled = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->sum('drl.price');
            $not_settled = $not_settled + 0;
            $map['drl.pay_state'] = ['eq', 1];
            $settled = $this->DealerRepairLog->alias('drl')
                ->join($prefix . 'car_dealer as cd ON drl.dealer_id = cd.dealer_id')
                ->join($prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
                ->where($map)->sum('drl.price');
            $settled = $settled + 0;
        }
        $result = [
            'type' => $type,
            'success_num' => $total_success,
            'cbs_success' => $cbs_success,
            'cjd_success' => $cjd_success,
            'c315_success' => $c315_success,
            'settled' => $settled,
            'not_settled' => $not_settled
        ];
        return $result;
    }


    /**
     * 获取维保查询第三方接口对账查询记录统计，查询次数，产生金额
     *
     * @param array $params
     *
     * @return array
     *
     */
//    public function get_third_repair_check_account_count($params)
//    {
//        $type = 0;
//        $yestoday = date("Y-m-d", strtotime('-1 day'));
//        $map['createtime'] = [['egt', $yestoday . ' 00:00:00'], ['elt', $yestoday . '23:59:59']];
//
//        $finance_price = SystemConf::getConfByName('REPAIR_FINANCE_SINGL_PRICE');
//        $finance_price = json_decode($finance_price['value'], true);
//        if ($params['vin']) {
//            $map['vin'] = ['eq', $params['vin']];
//        }
//        if ($params['check_platform']) {
//            $map['source'] = ['eq', $params['check_platform']];
//        }
//        if ($params['status'] == 2) {
//            $map['type'] = ['in', [1, 2]];
//        }
//        if ($params['start_time']) {
//            $map['createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
//            $type = 1;
//        }
//        if ($params['end_time']) {
//            $map['createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
//            $type = 2;
//        }
//        if ($params['start_time'] && $params['end_time']) {
//            $map['createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
//            $type = 3;
//        }
//        $map['search_state'] = ['eq', 2];
//        if ($params['third_channel'] > 0) {
//            $map['type'] = ['eq', $params['third_channel']];
//            $total_success = $this->ThirdRepairLog->where($map)->count();
//            if ($params['third_channel'] == 1) { //查博士
//                $cjd_total = 0;
//                $cjd_success = 0;
//                $map['type'] = ['eq', 1];
//                $cbs_success = $this->ThirdRepairLog->where($map)->count();
//                $cbs_total = $total_success * $finance_price['chaboshi'];
//            } elseif ($params['third_channel'] == 2) { //车鉴定
//                $cbs_total = 0;
//                $cbs_success = 0;
//                $map['type'] = ['eq', 2];
//                $cjd_success = $this->ThirdRepairLog->where($map)->count();
//                $cjd_total = $total_success * $finance_price['chejianding'];
//            }
//        } else {
//            $total_success = $this->ThirdRepairLog->where($map)->count();
//            $map['type'] = ['eq', 1];
//            $cbs_success = $this->ThirdRepairLog->where($map)->count();
//            $cbs_total = $cbs_success * $finance_price['chaboshi'];
//            $map['type'] = ['eq', 2];
//            $cjd_success = $this->ThirdRepairLog->where($map)->count();
//            $cjd_total = $cjd_success * $finance_price['chejianding'];
//        }
//        $result = [
//            'type' => $type,
//            'success_num' => $total_success,
//            'cbs_success' => $cbs_success,
//            'cjd_success' => $cjd_success,
//            'cbs_total' => $cbs_total,
//            'cjd_total' => $cjd_total
//        ];
//        return $result;
//    }
    public function get_third_repair_check_account_count($params)
    {
        $type = 0;
        if ($params['begintime']) {
            $type = 1;
        }
        if ($params['endtime']) {
            $type = 2;
        }
        if ($params['begintime'] && $params['endtime']) {
            $type = 3;
        }
        $uc = new UserCenter();
        $data = $uc->get_repair_check_list($params);
        $result = [
            'type' => $type,
            'success_num' => !empty($data['success_count']) ? $data['success_count'] : 0,
            'cbs_success' => !empty($data['cbs_count']) ?  $data['cbs_count'] : 0,
            'cjd_success' => !empty($data['cjd_count']) ? $data['cjd_count'] : 0,
        ];
        return $result;
    }


    /**
     * 获取维保查询第三方接口对账查询记录统计，查询次数，产生金额
     *
     * @param array $params
     *
     * @return array
     *
     */
    public function get_repair_info_check_account_count($params)
    {
        $type = 0;
        $yestoday = date("Y-m-d", strtotime('-1 day'));
        $map['createtime'] = [['egt', $yestoday . ' 00:00:00'], ['elt', $yestoday . '23:59:59']];

        $finance_price = SystemConf::getConfByName('REPAIR_FINANCE_SINGL_PRICE');
        $finance_price = json_decode($finance_price['value'], true);
        if ($params['vin']) {
            $map['vin'] = ['eq', $params['vin']];
        }
        if ($params['check_platform']) {
            $map['source'] = ['eq', $params['check_platform']];
        }
        if ($params['status'] == 2) {
            $map['type'] = ['in', [1, 2]];
        }
        if ($params['start_time']) {
            $map['createtime'] = ['egt', $params['start_time'] . ' 00:00:00'];
            $type = 1;
        }
        if ($params['end_time']) {
            $map['createtime'] = ['elt', $params['end_time'] . ' 23:59:59'];
            $type = 2;
        }
        if ($params['start_time'] && $params['end_time']) {
            $map['createtime'] = [['egt', $params['start_time'] . ' 00:00:00'], ['elt', $params['end_time'] . ' 23:59:59']];
            $type = 3;
        }
        $map['search_state'] = ['eq', 2];
        $prefix = C('DB_PREFIX');
        if ($params['third_channel'] > 0) {
            $map['type'] = ['eq', $params['third_channel']];
            $total_success = $this->ThirdRepairLog->where($map)->count();
            if ($params['third_channel'] == 1) { //查博士
                $cjd_total = 0;
                $cjd_success = 0;
                $map['type'] = ['eq', 1];
                $cbs_success = $this->ThirdRepairLog->where($map)->count();
                $cbs_total = $total_success * $finance_price['chaboshi'];
            } elseif ($params['third_channel'] == 2) { //车鉴定
                $cbs_total = 0;
                $cbs_success = 0;
                $map['type'] = ['eq', 2];
                $cjd_success = $this->ThirdRepairLog->where($map)->count();
                $cjd_total = $total_success * $finance_price['chejianding'];
            }
        } else {
            $total_success = $this->ThirdRepairLog->where($map)->count();
            $map['type'] = ['eq', 1];
            $cbs_success = $this->ThirdRepairLog->where($map)->count();
            $cbs_total = $cbs_success * $finance_price['chaboshi'];
            $map['type'] = ['eq', 2];
            $cjd_success = $this->ThirdRepairLog->where($map)->count();
            $cjd_total = $cjd_success * $finance_price['chejianding'];
        }
        $result = [
            'type' => $type,
            'success_num' => $total_success,
            'cbs_success' => $cbs_success,
            'cjd_success' => $cjd_success,
            'cbs_total' => $cbs_total,
            'cjd_total' => $cjd_total
        ];
        return $result;
    }

    /**
     * 保证金充值时结算维保透支金额
     *
     * @param $amount
     * @param $bail_log
     * @param $repair_log_id `
     * @param $dealer_id
     *
     * @return bool
     */
    public function the_bill($amount, $bail_log, $repair_log_id = 0, $dealer_id)
    {
        //查询起止和结束时间
        $prefix = C('DB_PREFIX');
        $sql = "SELECT createtime FROM {$prefix}dealer_repair_log WHERE dealer_id=" . $dealer_id . "
				and pay_state=0 and search_state=2 order by createtime asc";
        $result = M()->query($sql);

        $end = end($result);

        $first = reset($result);
        //查询次数
        $times = count($result);

        $map = array(
            'dealer_id' => $dealer_id,
            'pay_state' => 0,
            'search_state' => 2
        );
        //多次结算
        if ($repair_log_id) {
            $sql = "update {$prefix}dealer_repair_log set pay_state=1 where id in(select d.id from (select * from {$prefix}dealer_repair_log where dealer_id=" . $dealer_id . "
			and pay_state=0 and search_state=2 order by createtime desc LIMIT " . $repair_log_id . ") as d )";

            $pay_state = M()->execute($sql);
            $times = $repair_log_id;
        } else {
            //全部结算
            $pay_state = M('dealer_repair_log')->where($map)->save(array('pay_state' => 1));
        }

        $option = array(
            'end_time' => $end['createtime'],
            'start_time' => $first['createtime'],
            'times' => $times,
            'dealer_id' => $dealer_id,
            'amount' => $amount,
            'bl_id' => $bail_log,
            'createtime' => date('Y-m-d H:i:s')
        );
        $bill_state = M('dealer_repair_pay_log')->add($option);
        if ($bill_state && $pay_state) {
            return true;
        } else {
            return false;
        }
    }
}
